from flask import Flask, jsonify, request
from flask_swagger import swagger
from flask_swagger_ui import get_swaggerui_blueprint

app = Flask(__name__)

# 配置Swagger UI
SWAGGER_URL = '/swagger'  # Swagger UI访问路径
API_URL = '/swagger.json'  # Swagger JSON所在路径

# 创建Swagger UI蓝图
swaggerui_blueprint = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
    config={
        'app_name': "用户管理API"  # Swagger UI页面标题
    }
)

# 注册蓝图
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

# 模拟数据库
users = [
    {'id': 1, 'name': '张三', 'email': 'zhangsan@example.com'},
    {'id': 2, 'name': '李四', 'email': 'lisi@example.com'}
]
next_id = 3

@app.route('/swagger.json')
def spec():
    """生成Swagger规范JSON"""
    swag = swagger(app)
    swag['info']['version'] = "1.0"
    swag['info']['title'] = "用户管理API"
    swag['info']['description'] = "通过注释自动生成的用户管理API文档"
    return jsonify(swag)

@app.route('/users', methods=['GET'])
def get_users():
    """
    获取所有用户列表
    ---
    tags:
      - users
    responses:
      200:
        description: 成功返回用户列表
        schema:
          type: array
          items:
            type: object
            properties:
              id:
                type: integer
              name:
                type: string
              email:
                type: string
    """
    return jsonify(users)

@app.route('/users', methods=['POST'])
def create_user():
    """
    创建新用户
    ---
    tags:
      - users
    parameters:
      - in: body
        name: body
        required: true
        schema:
          type: object
          required:
            - name
            - email
          properties:
            name:
              type: string
            email:
              type: string
    responses:
      201:
        description: 用户创建成功
    """
    global next_id
    user = request.json
    user['id'] = next_id
    next_id += 1
    users.append(user)
    return jsonify(user), 201

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """
    根据ID获取用户信息
    ---
    tags:
      - 测试
    parameters:
      - name: user_id
        in: path
        type: integer
        required: true
    responses:
      200:
        description: 成功返回用户信息
      404:
        description: 用户不存在
    """
    for user in users:
        if user['id'] == user_id:
            return jsonify(user)
    return jsonify({"error": "用户不存在"}), 404

if __name__ == '__main__':
    app.run(debug=True)
